// 全局变量
let socket;
let isAutoScroll = true;
let currentLogTab = 'semantic_scholar';
let crawlerStatusData = {};
let crawlerLogs = {
    semantic_scholar: [],
    scholar: [],
    dblp: [],
    test: []
};

// 查看器相关变量
let currentResults = [];
let currentAuthorIndex = 0;
let currentViewerType = 'semantic_scholar';

// 初始化
document.addEventListener('DOMContentLoaded', function() {
    console.log('🚀 DOM加载完成，开始初始化...');
    
    initializeSocket();
    initializeEventListeners();
    initializeLogTabs();
    loadInitialStatus();
    updateResultsInfo();
    
    // 添加测试日志
    setTimeout(() => {
        console.log('📝 开始添加测试日志...');
        addLogEntry('系统初始化完成', 'success', 'semantic_scholar');
        addLogEntry('WebSocket连接准备就绪', 'info', 'semantic_scholar');
        addLogEntry('事件监听器已绑定', 'info', 'scholar');
        addLogEntry('日志系统正常运行', 'info', 'dblp');
        addLogEntry('测试爬虫日志系统', 'info', 'test');
        console.log('✅ 测试日志添加完成');
    }, 500);
    
    console.log('✅ 初始化完成');
});

// 初始化WebSocket连接
function initializeSocket() {
    console.log('🔌 开始初始化WebSocket连接...');
    
    try {
        socket = io();
        
        socket.on('connect', function() {
            console.log('🔌 WebSocket连接已建立');
            addLogEntry('WebSocket连接已建立', 'success', 'semantic_scholar');
            showNotification('已连接到服务器', 'success');
        });
        
        socket.on('disconnect', function() {
            console.log('❌ WebSocket连接已断开');
            addLogEntry('WebSocket连接已断开', 'error', 'semantic_scholar');
            showNotification('WebSocket连接已断开', 'error');
        });
        
        socket.on('crawler_status', function(data) {
            console.log('📊 收到爬虫状态更新:', data);
            updateCrawlerStatus(data.crawler_type, data);
        });
        
        socket.on('log_message', function(data) {
            console.log('📝 收到日志消息:', data);
            displayLogEntry({
                timestamp: data.timestamp,
                message: data.message,
                type: data.type || 'info'
            }, data.crawler_type);
        });
        
        console.log('✅ WebSocket初始化完成');
    } catch (error) {
        console.error('❌ WebSocket初始化失败:', error);
        addLogEntry('WebSocket初始化失败: ' + error.message, 'error', 'semantic_scholar');
        showNotification('WebSocket初始化失败: ' + error.message, 'error');
    }
}

// 初始化事件监听器
function initializeEventListeners() {
    console.log('🔧 开始初始化事件监听器...');
    
    // 爬虫按钮事件
    const crawlerBtns = document.querySelectorAll('.crawler-btn');
    crawlerBtns.forEach(btn => {
        btn.addEventListener('click', function() {
            const crawlerType = this.dataset.type;
            const crawlerName = this.dataset.name;
            startCrawler(crawlerType, crawlerName);
        });
    });
    
    // 停止所有按钮
    const stopAllBtn = document.getElementById('stopAllBtn');
    if (stopAllBtn) {
        stopAllBtn.addEventListener('click', function() {
            stopAllCrawlers();
        });
    }
    
    // 日志控制
    const clearLogsBtn = document.getElementById('clearLogsBtn');
    if (clearLogsBtn) {
        clearLogsBtn.addEventListener('click', function() {
            clearCurrentLogs();
        });
    }
    
    const exportLogsBtn = document.getElementById('exportLogsBtn');
    if (exportLogsBtn) {
        exportLogsBtn.addEventListener('click', function() {
            exportLogs();
        });
    }
    
    const autoScroll = document.getElementById('autoScroll');
    if (autoScroll) {
        autoScroll.addEventListener('change', function() {
            isAutoScroll = this.checked;
        });
    }
    
    // 结果查看器
    const loadResultsBtn = document.getElementById('loadResultsBtn');
    if (loadResultsBtn) {
        loadResultsBtn.addEventListener('click', function() {
            loadResults();
        });
    }
    
    const prevAuthor = document.getElementById('prevAuthor');
    if (prevAuthor) {
        prevAuthor.addEventListener('click', function() {
            previousAuthor();
        });
    }
    
    const nextAuthor = document.getElementById('nextAuthor');
    if (nextAuthor) {
        nextAuthor.addEventListener('click', function() {
            nextAuthor();
        });
    }
    
    // 日志标签页切换
    document.querySelectorAll('.log-tab').forEach(tab => {
        tab.addEventListener('click', function() {
            const crawlerType = this.dataset.crawler;
            switchLogTab(crawlerType);
        });
    });
    
    console.log('✅ 事件监听器初始化完成');
    
    // 键盘快捷键
    document.addEventListener('keydown', function(e) {
        // Ctrl+1: Semantic Scholar
        if (e.ctrlKey && e.key === '1') {
            e.preventDefault();
            startCrawler('semantic_scholar', 'Semantic Scholar');
        }
        // Ctrl+2: Scholar
        else if (e.ctrlKey && e.key === '2') {
            e.preventDefault();
            startCrawler('scholar', 'Scholar');
        }
        // Ctrl+3: DBLP
        else if (e.ctrlKey && e.key === '3') {
            e.preventDefault();
            startCrawler('dblp', 'DBLP');
        }
        // Ctrl+4: 测试爬虫
        else if (e.ctrlKey && e.key === '4') {
            e.preventDefault();
            startCrawler('test', '测试爬虫');
        }
        // Ctrl+S: 停止所有
        else if (e.ctrlKey && e.key === 's') {
            e.preventDefault();
            stopAllCrawlers();
        }
        // 左右箭头键：在查看器中切换作者
        else if (e.key === 'ArrowLeft') {
            e.preventDefault();
            previousAuthor();
        }
        else if (e.key === 'ArrowRight') {
            e.preventDefault();
            nextAuthor();
        }
    });
}

// 初始化日志标签页
function initializeLogTabs() {
    document.querySelectorAll('.log-tab').forEach(tab => {
        tab.addEventListener('click', function() {
            const crawlerType = this.dataset.crawler;
            switchLogTab(crawlerType);
        });
    });
    
    // 初始渲染所有日志
    renderAllLogs();
}

// 渲染所有爬虫的日志
function renderAllLogs() {
    Object.keys(crawlerLogs).forEach(crawlerType => {
        renderLogsForCrawler(crawlerType);
    });
}

// 切换日志标签页
function switchLogTab(crawlerType) {
    console.log('🔄 切换日志标签页到:', crawlerType);
    
    // 更新标签页状态
    document.querySelectorAll('.log-tab').forEach(tab => {
        tab.classList.remove('active');
    });
    const activeTab = document.querySelector(`.log-tab[data-crawler="${crawlerType}"]`);
    if (activeTab) {
        activeTab.classList.add('active');
    }
    
    // 更新日志面板
    document.querySelectorAll('.log-panel').forEach(panel => {
        panel.classList.remove('active');
    });
    const activePanel = document.querySelector(`.log-panel[data-crawler="${crawlerType}"]`);
    if (activePanel) {
        activePanel.classList.add('active');
    }
    
    currentLogTab = crawlerType;
    
    // 滚动到底部
    if (isAutoScroll) {
        scrollToBottom();
    }
    
    console.log('✅ 日志标签页切换完成');
}

// 重新渲染指定爬虫的日志
function renderLogsForCrawler(crawlerType) {
    const logContainer = document.getElementById(`${crawlerType}_logs`);
    if (!logContainer) return;
    
    // 保存滚动位置
    const scrollPosition = logContainer.scrollTop;
    const scrollHeight = logContainer.scrollHeight;
    
    // 清空当前容器
    logContainer.innerHTML = '';
    
    // 渲染所有日志条目
    crawlerLogs[crawlerType].forEach(logEntry => {
        displayLogEntry(logEntry, crawlerType);
    });
    
    // 恢复滚动位置
    if (scrollPosition > 0) {
        logContainer.scrollTop = scrollPosition;
    } else if (isAutoScroll) {
        scrollToBottom();
    }
}

// 启动爬虫
async function startCrawler(crawlerType, crawlerName) {
    const startIndex = parseInt(document.getElementById('startIndex').value) || 1;
    
    try {
        // 检查爬虫是否已在运行
        if (crawlerStatusData[crawlerType] && crawlerStatusData[crawlerType].is_running) {
            showNotification(`${crawlerName}爬虫已在运行中`, 'warning');
            return;
        }
        
        // 更新按钮状态
        const btn = document.querySelector(`[data-type="${crawlerType}"]`);
        if (btn) {
            btn.classList.add('running');
            btn.innerHTML = `<span class="loading"></span> 启动中...`;
        }
        
        const response = await fetch('/api/start_crawler', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ 
                crawler_type: crawlerType,
                start_index: startIndex 
            })
        });
        
        const data = await response.json();
        
        if (data.success) {
            showNotification(data.message, 'success');
            // 切换到对应爬虫的日志标签页
            switchLogTab(crawlerType);
        } else {
            showNotification(data.message, 'error');
            resetCrawlerButton(crawlerType);
        }
    } catch (error) {
        showNotification('启动爬虫失败: ' + error.message, 'error');
        resetCrawlerButton(crawlerType);
    }
}

// 停止所有爬虫
async function stopAllCrawlers() {
    try {
        const response = await fetch('/api/stop_crawler', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ crawler_type: 'all' })
        });
        
        const data = await response.json();
        showNotification(data.message, data.success ? 'success' : 'error');
        
        if (data.success) {
            // 重置所有爬虫按钮
            document.querySelectorAll('.crawler-btn').forEach(btn => {
                resetCrawlerButton(btn.dataset.type);
            });
        }
    } catch (error) {
        showNotification('停止爬虫失败: ' + error.message, 'error');
    }
}

// 重置爬虫按钮
function resetCrawlerButton(crawlerType) {
    const btn = document.querySelector(`[data-type="${crawlerType}"]`);
    if (btn) {
        btn.classList.remove('running');
        const crawlerName = btn.dataset.name;
        btn.innerHTML = `
            <span class="btn-icon">${getCrawlerIcon(crawlerType)}</span>
            <span class="btn-text">${crawlerName}</span>
            <span class="btn-shortcut">${getCrawlerShortcut(crawlerType)}</span>
        `;
    }
}

// 获取爬虫图标
function getCrawlerIcon(crawlerType) {
    const icons = {
        'semantic_scholar': '📚',
        'scholar': '👨‍🎓',
        'dblp': '🗄️',
        'test': '🧪'
    };
    return icons[crawlerType] || '🤖';
}

// 获取爬虫快捷键
function getCrawlerShortcut(crawlerType) {
    const shortcuts = {
        'semantic_scholar': 'Ctrl+1',
        'scholar': 'Ctrl+2',
        'dblp': 'Ctrl+3',
        'test': 'Ctrl+4'
    };
    return shortcuts[crawlerType] || '';
}

// 更新爬虫状态
function updateCrawlerStatus(crawlerType, data) {
    const statusCard = document.querySelector(`.status-card[data-crawler="${crawlerType}"]`);
    if (!statusCard) return;
    
    // 更新状态指示器
    const indicator = statusCard.querySelector('.status-indicator');
    const statusText = statusCard.querySelector('.status-text');
    const processed = statusCard.querySelector('.processed');
    const runtime = statusCard.querySelector('.runtime');
    
    // 根据状态更新样式
    const statusClass = data.status === 'running' ? 'running' : 
                      data.status === 'completed' ? 'completed' :
                      data.status === 'error' ? 'error' :
                      data.status === 'stopped' ? 'stopped' : 'idle';
    
    indicator.className = `status-indicator ${statusClass}`;
    
    // 更新状态文本
    statusText.textContent = data.status === 'running' ? '运行中' : 
                           data.status === 'completed' ? '已完成' :
                           data.status === 'error' ? '错误' :
                           data.status === 'stopped' ? '已停止' : '空闲';
    
    // 更新处理数量
    if (data.processed_count !== undefined) {
        processed.textContent = data.processed_count;
    }
    
    // 更新运行时间
    if (data.start_time && data.status === 'running') {
        const startTime = new Date(data.start_time);
        const elapsed = Math.floor((new Date() - startTime) / 1000);
        const mins = Math.floor(elapsed / 60);
        const secs = elapsed % 60;
        runtime.textContent = `${mins}分 ${secs}秒`;
    } else {
        runtime.textContent = '-';
    }
    
    // 更新按钮状态
    if (data.status === 'running') {
        const btn = document.querySelector(`.crawler-btn[data-type="${crawlerType}"]`);
        if (btn) {
            btn.classList.add('running');
        }
    } else {
        resetCrawlerButton(crawlerType);
    }
    
    // 显示通知
    if (data.message) {
        showNotification(data.message, data.status === 'error' ? 'error' : 'success');
    }
}

// 添加日志条目
function addLogEntry(message, type = 'info', crawlerType = currentLogTab) {
    const timestamp = new Date().toLocaleTimeString();
    
    // 存储日志
    if (!crawlerLogs[crawlerType]) {
        crawlerLogs[crawlerType] = [];
    }
    
    const logEntry = {
        timestamp: timestamp,
        message: message,
        type: type
    };
    
    crawlerLogs[crawlerType].push(logEntry);
    
    // 保持日志数量在合理范围内
    if (crawlerLogs[crawlerType].length > 1000) {
        crawlerLogs[crawlerType] = crawlerLogs[crawlerType].slice(-500);
    }
    
    // 显示日志条目
    displayLogEntry(logEntry, crawlerType);
}

// 显示日志条目
function displayLogEntry(logEntry, crawlerType) {
    // 尝试多种可能的容器ID
    let logContainer = document.getElementById(`${crawlerType}_logs`);
    if (!logContainer) return;
    
    const logElement = document.createElement('div');
    logElement.className = `log-entry log-${logEntry.type}`;
    
    const timestampSpan = document.createElement('span');
    timestampSpan.className = 'log-timestamp';
    timestampSpan.textContent = `[${logEntry.timestamp}]`;
    
    const messageSpan = document.createElement('span');
    messageSpan.className = 'log-message';
    messageSpan.textContent = logEntry.message;
    
    logElement.appendChild(timestampSpan);
    logElement.appendChild(messageSpan);
    
    logContainer.appendChild(logElement);
    
    // 如果是当前活动的标签页且启用了自动滚动，则滚动到底部
    if (currentLogTab === crawlerType && isAutoScroll) {
        scrollToBottom();
    }
}

// 滚动到底部
function scrollToBottom() {
    const activeLogContent = document.querySelector('.log-panel.active .log-content');
    if (activeLogContent) {
        activeLogContent.scrollTop = activeLogContent.scrollHeight;
    }
}

// 清空当前日志
async function clearCurrentLogs() {
    try {
        const response = await fetch(`/api/clear_logs/${currentLogTab}`);
        const data = await response.json();
        
        if (data.success) {
            const logContainer = document.getElementById(`${currentLogTab}_logs`);
            if (logContainer) {
                logContainer.innerHTML = '';
            }
            crawlerLogs[currentLogTab] = [];
            showNotification(data.message, 'success');
        } else {
            showNotification(data.message, 'error');
        }
    } catch (error) {
        showNotification('清空日志失败: ' + error.message, 'error');
    }
}

// 导出日志
function exportLogs() {
    const logs = crawlerLogs[currentLogTab] || [];
    if (logs.length === 0) {
        showNotification('没有日志可导出', 'warning');
        return;
    }
    
    const logText = logs.map(log => `[${log.timestamp}] ${log.message}`).join('\n');
    const blob = new Blob([logText], { type: 'text/plain' });
    const url = URL.createObjectURL(blob);
    
    const a = document.createElement('a');
    a.href = url;
    a.download = `${currentLogTab}_logs_${new Date().toISOString().slice(0, 19).replace(/:/g, '-')}.txt`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
    
    showNotification('日志导出成功', 'success');
}

// 加载初始状态
async function loadInitialStatus() {
    try {
        const response = await fetch('/api/status');
        const data = await response.json();
        
        crawlerStatusData = data.crawlers || {};
        
        // 更新状态卡片
        Object.keys(crawlerStatusData).forEach(crawlerType => {
            const status = crawlerStatusData[crawlerType];
            if (status.is_running) {
                updateCrawlerStatus(crawlerType, {
                    status: 'running',
                    processed_count: status.processed_count,
                    start_time: status.start_time
                });
            }
        });
    } catch (error) {
        console.error('❌ 加载初始状态失败:', error);
    }
}

// 结果查看器相关函数
async function loadResults() {
    const resultType = document.getElementById('resultType').value;
    
    try {
        const response = await fetch(`/api/results/${resultType}`);
        const data = await response.json();
        
        if (data.success) {
            currentResults = data.results;
            currentAuthorIndex = 0;
            currentViewerType = resultType;
            
            updateResultsInfo(data);
            showAuthorCard();
            
            showNotification(`成功加载 ${resultType} 结果文件，共 ${data.count} 条记录`, 'success');
        } else {
            showNotification(data.message, 'error');
        }
    } catch (error) {
        showNotification('加载结果失败: ' + error.message, 'error');
    }
}

function updateResultsInfo(data) {
    document.getElementById('fileStatus').textContent = '已加载';
    document.getElementById('recordCount').textContent = data.count;
    document.getElementById('fileSize').textContent = formatFileSize(data.count * 1000); // 估算文件大小
}

function formatFileSize(bytes) {
    if (bytes === 0) return '0 Bytes';
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

function showAuthorCard() {
    const authorCard = document.getElementById('authorCard');
    const currentAuthor = document.getElementById('currentAuthor');
    const authorIndex = document.getElementById('authorIndex');
    const prevBtn = document.getElementById('prevAuthor');
    const nextBtn = document.getElementById('nextAuthor');
    
    if (currentResults.length === 0) {
        authorCard.innerHTML = `
            <div class="card-placeholder">
                <span class="placeholder-icon">👤</span>
                <span class="placeholder-text">请加载结果文件查看作者信息</span>
            </div>
        `;
        currentAuthor.textContent = '未选择作者';
        authorIndex.textContent = '0 / 0';
        prevBtn.disabled = true;
        nextBtn.disabled = true;
        return;
    }
    
    const authorData = currentResults[currentAuthorIndex];
    const authorName = getAuthorName(authorData);
    
    currentAuthor.textContent = authorName;
    authorIndex.textContent = `${currentAuthorIndex + 1} / ${currentResults.length}`;
    
    prevBtn.disabled = currentAuthorIndex === 0;
    nextBtn.disabled = currentAuthorIndex === currentResults.length - 1;
    
    authorCard.innerHTML = renderAuthorData(authorData);
}

function getAuthorName(authorData) {
    return authorData.name || authorData.author_name || '未知作者';
}

function renderAuthorData(authorData) {
    switch (currentViewerType) {
        case 'semantic_scholar':
            return renderSemanticScholarData(authorData);
        case 'scholar':
            return renderScholarData(authorData);
        case 'dblp':
            return renderDBLPData(authorData);
        default:
            return `<pre>${JSON.stringify(authorData, null, 2)}</pre>`;
    }
}

function renderSemanticScholarData(authorData) {
    return `
        <div class="author-header">
            <h3>${authorData.name || '未知作者'}</h3>
            <p>ID: ${authorData.author_id || 'N/A'}</p>
        </div>
        <div class="author-details">
            <p><strong>论文数量:</strong> ${authorData.paper_count || 0}</p>
            <p><strong>引用次数:</strong> ${authorData.citation_count || 0}</p>
            <p><strong>H指数:</strong> ${authorData.h_index || 0}</p>
            <p><strong>主页:</strong> <a href="${authorData.homepage || '#'}" target="_blank">${authorData.homepage || 'N/A'}</a></p>
        </div>
    `;
}

function renderScholarData(authorData) {
    const sources = authorData.sources || {};
    return `
        <div class="author-header">
            <h3>${authorData.name || '未知作者'}</h3>
        </div>
        <div class="author-details">
            <div class="source-section">
                <h4>DBLP 数据</h4>
                <p>论文数量: ${sources.dblp?.publication_count || 0}</p>
            </div>
            <div class="source-section">
                <h4>ORCID 数据</h4>
                <p>档案数量: ${sources.orcid?.profile_count || 0}</p>
            </div>
            <div class="source-section">
                <h4>GitHub 数据</h4>
                <p>用户名: ${sources.github?.profile?.login || 'N/A'}</p>
            </div>
        </div>
    `;
}

function renderDBLPData(authorData) {
    return `
        <div class="author-header">
            <h3>${authorData.name || '未知作者'}</h3>
        </div>
        <div class="author-details">
            <p><strong>URL:</strong> <a href="${authorData.url || '#'}" target="_blank">${authorData.url || 'N/A'}</a></p>
        </div>
    `;
}

function previousAuthor() {
    if (currentAuthorIndex > 0) {
        currentAuthorIndex--;
        showAuthorCard();
    }
}

function nextAuthor() {
    if (currentAuthorIndex < currentResults.length - 1) {
        currentAuthorIndex++;
        showAuthorCard();
    }
}

async function updateResultsInfo() {
    try {
        const response = await fetch('/api/results');
        const data = await response.json();
        
        if (data.success) {
            // 更新结果文件状态显示
            console.log('📊 结果文件信息:', data.results);
        }
    } catch (error) {
        console.error('❌ 获取结果信息失败:', error);
    }
}

// 显示通知
function showNotification(message, type = 'info') {
    const container = document.getElementById('notificationContainer');
    const notification = document.createElement('div');
    notification.className = `notification ${type}`;
    notification.textContent = message;
    
    container.appendChild(notification);
    
    setTimeout(() => {
        notification.style.opacity = '0';
        setTimeout(() => {
            container.removeChild(notification);
        }, 300);
    }, 3000);
}

// 页面卸载时清理
window.addEventListener('beforeunload', function() {
    if (socket) {
        socket.disconnect();
    }
});